package root;

import common.CommandTypeEnum;
import common.MonitorTcpDataPackage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.util.logging.Logger;

//@Slf4j
public class MonitorTcpSocket {
    Logger log=Logger.getLogger("MonitorTcpSocket");
    ServerSocket serverSocket;
    int port=1280;
    MonitorFunctionServiceImpl monitorFunctionService=MonitorFunctionServiceImpl.getInstance();

    public MonitorTcpSocket() throws IOException {
        this.serverSocket=new ServerSocket(port);
        log.info("创捷TCP接口成功，端口是："+port);
    }

    public void acceptDatePackage() throws IOException {
        while (serverSocket!=null){
            log.info("正在等待数据。。。。");
            var acceptData = serverSocket.accept();
            var acceptInputStream=acceptData.getInputStream();
            var outputStream=acceptData.getOutputStream();
            try {
                var dataPackage=(MonitorTcpDataPackage) new ObjectInputStream(acceptInputStream).readObject();
                switch (dataPackage.getCommandTypeEnum()) {
                    case PING -> pingMsg(outputStream);
                    case STRING -> stringMsg(dataPackage,outputStream);
                    case VERSION_CODE->versionCodeMsg(outputStream);
                }
            } catch (Exception e) {
                log.warning("异常："+e.getMessage());
                e.printStackTrace();
            }
        }
    }
    public void pingMsg(OutputStream outputStream) throws IOException {
        var resultPackage=new MonitorTcpDataPackage();
        resultPackage.setCommandTypeEnum(CommandTypeEnum.PONG);
        System.out.println("PING");
        respondData(resultPackage,outputStream);
    }
    public void versionCodeMsg(OutputStream outputStream) throws IOException {
        var resultPackage=new MonitorTcpDataPackage();
        resultPackage.setCommandTypeEnum(CommandTypeEnum.RESPONDED);
        resultPackage.setNumberData((long) monitorFunctionService.getVersionCode());
        respondData(resultPackage,outputStream);
    }
    public void stringMsg(MonitorTcpDataPackage monitorTcpDataPackage,OutputStream outputStream) throws IOException {
        var resultPackage=new MonitorTcpDataPackage();
        System.out.println(monitorTcpDataPackage.getStringData());
        resultPackage.setCommandTypeEnum(CommandTypeEnum.RESPONDED);
        respondData(resultPackage,outputStream);
    }

    public void respondData(MonitorTcpDataPackage resultPackage,OutputStream outputStream) throws IOException {
        var objectOutputStream=new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(resultPackage);
        objectOutputStream.flush();
        objectOutputStream.close();
    }
}
